package TestPark;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import jdbcutil.JDBCUtil;

public class ParkingSpaceDao {
	Connection conn = null;
	PreparedStatement ps = null;
	
	public Integer insert(ParkingSpaceModel model) {
		String sql = "insert into test.parking(id,status)values(?,?)";
		try {
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, model.getId());
			ps.setInt(2, model.getStatus());
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps);
		}
		return null;
	}
	
	public List<ParkingSpaceModel> selectList() {
		List<ParkingSpaceModel> list = new ArrayList<>();
		StringBuffer sql = new StringBuffer("select id,status from test.parking");
		ResultSet rs = null;
		try {
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(sql.toString());
			rs = ps.executeQuery();
			while (rs.next()) {
				ParkingSpaceModel mod = new ParkingSpaceModel();
				mod.setId(rs.getInt("id"));
				mod.setStatus(rs.getInt("status"));
				list.add(mod);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps, rs);
		}
		return list;
	}
	
	public Integer update(ParkingSpaceModel model) {
		StringBuffer sql = new StringBuffer("update test.parking");
		List<Object> vals = appendSet(sql,model);
		System.out.println(sql);
		try {
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(sql.toString());
			for (int i = 0; i < vals.size(); i++) {
				ps.setObject(i + 1, vals.get(i));
			}
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps);
		}
		return null;
	}
	
	private List<Object> appendSet(StringBuffer sql, ParkingSpaceModel model) {
		sql.append(" set id = id ");
		List<Object> objs = new ArrayList<Object>();
		int status = model.getStatus();
		sql.append(",status = ? ");
		objs.add(status);

		int id = model.getId();
		sql.append("where id = ? ");
		objs.add(id);
		return objs;
	}
	
}
